package com.jt.www.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jt.www.exception.BizException;
import com.jt.www.model.reps.uploadRemote.UploadFileRespResp;
import com.jt.www.model.reps.uploadRemote.UploadRespResp;
import com.jt.www.remote.FilesNewClient;
import com.thoughtworks.xstream.core.util.Base64Encoder;
import feign.Response;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class RemoteFileUtils {

    private static FilesNewClient filesClient;
    private static ConfigUtils configUtils;
    private static ObjectMapper objectMapper;
    private final FilesNewClient fc;
    private final ConfigUtils cfu;
    private final ObjectMapper om;

    @Autowired
    public RemoteFileUtils(FilesNewClient fc, ConfigUtils cfu, ObjectMapper om) {
        this.fc = fc;
        this.cfu = cfu;
        this.om = om;
    }

    /**
     * 上传文件到远程服务器
     *
     * @param files 文件
     * @return 文件信息：文件id，文件名，resCode
     */
    public static List<UploadFileRespResp> upLoadFile(MultipartFile[] files) {
        String urlRemote = filesClient.batchupload(files, configUtils.getChannelCode(), "I001", "", "");
        UploadRespResp uploadRespResp;
        try {
            uploadRespResp = objectMapper.readValue(urlRemote, UploadRespResp.class);
        } catch (IOException e) {
            throw new BizException("远程文件上传，返回结果解析异常");
        }
        if (uploadRespResp == null || uploadRespResp.getList() == null || uploadRespResp.getList().isEmpty()) {
            throw new BizException("远程文件上传，返回ID为空");
        }
        return uploadRespResp.getList();
    }

    /**
     * 从文件服务器获取图片
     *
     * @param fileId 图片id
     * @return 图片地址
     */
    public static String getUrlByFileId(String fileId) {
        if (fileId != null && !fileId.isEmpty()) {
            return configUtils.getFileUrl() +
                    fileId;

            //test用
//            return "http://res-svc-dev.jiangtai.com" +
//                    "/res/download?fileId=" +
//                    fileId;
        }
        return "";
    }

    /**
     * 从文件服务器获取图片
     *
     * @param fileId 图片id
     * @return Base64编码的图片
     */
    public static String getUrlEncode(String fileId) {
        if (fileId != null && !fileId.isEmpty()) {
            // 编码
            Base64Encoder encoder = new Base64Encoder();
            Response response = filesClient.downloadFile(Long.valueOf(fileId));

            try (InputStream stream = response.body().asInputStream()) {

                byte[] bytes = CommonUtils.readStream(stream);
                return encoder.encode(bytes);
            } catch (IOException | NumberFormatException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * @param fileId 图片id
     * @return url:base64图片，图height像素值，图width像素值
     */
    public static Map<String, Object> getImageForReport(String fileId) {
        if (fileId != null && !fileId.isEmpty()) {
            Map<String, Object> map = new HashMap<>();
            map.put("name", fileId);
            // 编码
            Base64Encoder encoder = new Base64Encoder();
            Response response = filesClient.downloadFile(Long.valueOf(fileId));
            try (InputStream stream = response.body().asInputStream()) {
                byte[] bytes = CommonUtils.readStream(stream);
                String encode = encoder.encode(bytes);
                map.put("url", encode);

                BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(bytes));
                if (bufferedImage != null) {
                    // 单位为 px
                    int width = bufferedImage.getWidth();
                    int height = bufferedImage.getHeight();

                    // 按比例调整图片大小
                    if (width <= 480) {
                        map.put("width", width);
                        map.put("height", height);
                    } else {
                        double rate = (double) height / width;
                        map.put("width", 480);
                        map.put("height", 480 * rate);
                    }
                }

                return map;
            } catch (IOException | NumberFormatException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static MultipartFile downloadFile(String fileId, String appCode) throws IOException {
        Response response = filesClient.downloadFile(Long.valueOf(fileId));
        Collection<String> a = response.headers().get("content-disposition");
        String fileName1 = appCode + ".";
        String fileName = "";
        if (null != a) {
            for (String b : a) {
                String[] str = b.split(";");
                for (int i = 0; i < str.length; i++) {
                    if (str[i].startsWith("fileName=")) {
                        //取出来的是乱码不过不重要，只需要最后的扩展名就好
                        fileName += str[i].split("=")[1].split("\\.")[1];
                        break;
                    }
                }
            }
        }

        if (StringUtils.isBlank(fileName)) {
            fileName = fileName1 + "xls";
        } else {
            fileName = fileName1 + fileName;
        }

        InputStream inputStream = response.body().asInputStream();
        MultipartFile multipartFile = new MockMultipartFile("file", fileName, "", inputStream);
        return multipartFile;
    }

    @PostConstruct
    public void init() {
        filesClient = this.fc;
        configUtils = this.cfu;
        objectMapper = this.om;
    }
}
